package forward_port

import (
	"context"
	"net/http"
	"strings"
)

// Config the plugin configuration.
type Config struct {
}

// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
	return &Config{
	}
}

// New created a new forward-port plugin.
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
	return &ForwardPort{
		next: next,
		name: name,
	}, nil
}

// ForwardPort plugin
type ForwardPort struct {
	next http.Handler
	name string
}

func (f *ForwardPort) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	arr := strings.Split(request.RemoteAddr, ":")
	if len(arr) == 2 {
		port := arr[1]
		request.Header.Set("X-Real-Port", port)
	}

	f.next.ServeHTTP(writer, request)
}

var _ http.Handler = (*ForwardPort)(nil)
